package com.dly.hope.config;

import com.dly.hope.constant.ExceptionConstant;
import com.dly.hope.servce.JwtService;
import com.dly.hope.utils.CommonUtil;
import com.dly.hope.utils.ExceptionPropertiesUtil;
import com.dly.hope.vo.UserDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.Optional;

/**
 * @author linyu.dai
 * @project myserve
 * @description 自动注入
 * @creat 2022/8/26 10:59:56
 */
@Configuration
public class JpaAuditorGenerateConfig implements AuditorAware<String> {

    @Resource
    private JwtService jwtService;

    @Value("${jwt.header}")
    private String jwtHeader;

    /**
     * 用来注入 createUser 等信息
     */
    @Override
    public Optional<String> getCurrentAuditor() {

        //获取请求 request
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if(Objects.isNull(requestAttributes)){
            return Optional.empty();
        }
        ServletRequestAttributes sra = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = sra.getRequest();
        //获取token
        String token = CommonUtil.getToken(request, jwtHeader);
        /**
         * 如果token为空 返回创建人为空
         */
        if (StringUtils.isBlank(token)) {
            return Optional.empty();
        }
        //解析token
        UserDTO userDTO = jwtService.unSign(token);
        //设置创建人和更改人
        return Optional.of(userDTO.getId());
    }

}
